package com.xuanwu.ai.flow.component;

import com.alibaba.fastjson.JSONObject;
import com.xuanwu.ai.flow._enum.ErrorCodeEnum;
import com.xuanwu.ai.flow.constant.GlobalConstant;
import com.xuanwu.ai.flow.dto.CmpDataDTO;
import com.xuanwu.ai.flow.dto.CommonContextDTO;
import com.xuanwu.ai.flow.sao.AIDetectSao;
import com.xuanwu.ai.flow.sao.req.MergePredictionReq;
import com.xuanwu.ai.flow.utils.NodeDataUtils;
import com.xuanwu.ai.web.exception.BizException;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeIfComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@LiteflowComponent(name = "图片拼接预测条件组件", value = "mergePredictionIFCmp")
@Slf4j
public class MergePredictionIFCmp extends NodeIfComponent {
    @Autowired
    private AIDetectSao aiDetectSao;

    @Override
    public boolean processIf(){
        CommonContextDTO customContext = this.getContextBean(CommonContextDTO.class);
        if (customContext.getToken() == null) {
            throw new BizException(ErrorCodeEnum.NO_VALID_TOKEN);
        }
        MergePredictionReq mergePredictionReq = new MergePredictionReq();
        mergePredictionReq.setUrls(customContext.getUrls());
        JSONObject jsonObject = aiDetectSao.mergePrediction(customContext.getToken(), mergePredictionReq);
        log.info("拼接预测结果:{}", jsonObject.getJSONObject("data"));
        // 设置节点数据
        NodeDataUtils.setStepNodeData(customContext, this.getCmpData(CmpDataDTO.class).getUuid(), this.getName(), jsonObject);

        if(jsonObject.getInteger("status").equals(GlobalConstant.CMP_EXECUTE_FAIL)){
            throw new BizException(ErrorCodeEnum.CMP_EXECUTE_FAIL, this.getName());
        }

        return !jsonObject.getJSONObject("data").getJSONArray("ableToMerge").isEmpty();
    }

}
